package concurrency.chapter7;

public class SynchronizedThis {
    private final static Object LOCK = new Object();

    public static void main(String[] args) {
        ThisLock thisLock = new ThisLock();
        new Thread("T1") {
            @Override
            public void run() {
                thisLock.m1();
            }
        }.start();
        new Thread("T2") {
            @Override
            public void run() {
                thisLock.m2();
            }
        }.start();
    }
}

class ThisLock {
    private final Object LOCK =new Object();
    public synchronized void m1() {
        System.out.println(Thread.currentThread().getName());
        try {
            Thread.sleep(10_000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    //synchronized方法，必须等到第一个线程结束才能执行
    //public synchronized void m2() {
    public void m2() {
        //m1拿的是this锁，m2拿的是LOCK，不一样，不会等待
        synchronized (LOCK) {
            System.out.println(Thread.currentThread().getName());
            try {
                Thread.sleep(10_000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
